<template>
	<view class="">
		<u-toast ref="uToast"></u-toast>
		<u-popup :closeOnClickOverlay="false" :closeable="true" :show="showUploadPop" mode="top"
			@close="showUploadPop = false" @open="">
			<view style="padding: 40rpx">
				<u-loading-icon text="文件上传中" textSize="18" size="18" style="margin-bottom: 20rpx"></u-loading-icon>
				<u-line-progress :percentage="percentage"></u-line-progress>
			</view>
		</u-popup>
		<view class="wrap">
			<u-form class="form" :model="model" ref="uForm" :labelStyle="form_label_Style" labelPosition="left"
				labelWidth="100">
				<u-form-item borderBottom label="编号" prop="ProblemCode" v-if="model.id"
					:customStyle="form_item_customStyle">
					<u-input :readonly="isReadonly" v-model="model.ProblemCode" type="text" maxlength="64"
						border="none"></u-input>
				</u-form-item>
				<u-form-item @tap="refInputClick('pk_org')" borderBottom label="所属组织" prop="pk_org"
					class="form-item-wrap" :customStyle="form_item_customStyle">
					<gf-input-ref :docType="$GC.BASEDOC.ORG" :readonly="isReadonly" clearable placeholder="请输入"
						v-model="model.pk_org" type="text" maxlength="200" border="none"></gf-input-ref>
				</u-form-item>
				<!-- <u-form-item borderBottom label="问题标题" prop="ProblemTitle" class="form-item-wrap" :customStyle="form_item_customStyle">
					<u-input :readonly="isReadonly" clearable placeholder="请输入" v-model="model.ProblemTitle" type="text" maxlength="200" border="none"></u-input>
				</u-form-item> -->
				<u-form-item borderBottom label="发现人" prop="ProblemFindByPsn" :customStyle="form_item_customStyle">
					<gf-input-ref :docType="$GC.BASEDOC.SM_USER" :readonly="true" placeholder="请输入"
						v-model="model.ProblemFindByPsn" type="text" maxlength="200" border="none"></gf-input-ref>
				</u-form-item>
				<u-form-item borderBottom label="记录时间" prop="ProblemCreDate" :customStyle="form_item_customStyle">
					<u-input readonly placeholder="请输入" v-model="model.ProblemCreDate" type="text" maxlength="200"
						border="none"></u-input>
				</u-form-item>
				<u-form-item @tap="pickerInputEvent('ProblemType')" borderBottom label="问题类型" prop="ProblemType"
					:customStyle="form_item_customStyle">
					<gf-input-ref :readonly="isReadonly" clearable placeholder="请输入" v-model="model.ProblemType"
						type="text" maxlength="200" border="none"></gf-input-ref>
				</u-form-item>
				<u-form-item @tap="refInputClick('ProblemWorkProcedure')" borderBottom label="所属工序" prop="ProblemWorkProcedure"
					:customStyle="form_item_customStyle">
					<gf-input-ref suffixIcon="arrow-right" :docType="$GC.BASEDOC.WorkProcedure" :readonly="isReadonly"
						clearable placeholder="请输入" v-model="model.ProblemWorkProcedure" type="text" maxlength="200"
						border="none"></gf-input-ref>
				</u-form-item>
				<u-form-item @tap="refInputClick('ProblemClassify')" borderBottom label="所属班组" prop="ProblemClassify"
					:customStyle="form_item_customStyle">
					<gf-input-ref suffixIcon="arrow-right" :docType="$GC.BASEDOC.ClassGroup" :readonly="isReadonly"
						clearable placeholder="请输入" v-model="model.ProblemClassify" type="text" maxlength="200"
						border="none"></gf-input-ref>
				</u-form-item>
				<u-form-item @tap="refInputClick('ProblemZnjcFilter')" borderBottom label="类型负责人" prop="ProblemZnjcFilter"
					:customStyle="form_item_customStyle">
					<gf-input-ref suffixIcon="arrow-right" :docType="$GC.BASEDOC.PSNDOC" :readonly="isReadonly"
						clearable placeholder="请输入" v-model="model.ProblemZnjcFilter" type="text" maxlength="200"
						border="none"></gf-input-ref>
				</u-form-item>
				<u-form-item borderBottom label="问题描述" prop="ProblemDescription" label-position="top"
					:customStyle="form_item_customStyle">
					<u--textarea maxlength="1000" autoHeight :count="true" :disabled="isReadonly"
						v-model="model.ProblemDescription" border="none" placeholder="请输入"></u--textarea>
				</u-form-item>
				<!-- <u-form-item borderBottom label="录音" prop="ProblemVoice" label-position="left" left-icon="volume" :customStyle="form_item_customStyle">
					<u-button :plain="true" style="width: 100px" type="success" size="mini" @click="">播放录音</u-button>
				</u-form-item> -->
				<u-form-item borderBottom label="现场图片" prop="ProblemPicture" labelPosition="top"
					:customStyle="form_item_customStyle">
					<view class="u-page__upload-item">
						<u-upload :fileList="problemPicFileList" @afterRead="afterRead" @delete="deletePic"
							name="uploadPicture" multiple :maxCount="0" :previewFullImage="true"></u-upload>
					</view>
				</u-form-item>
				<u-form-item borderBottom label="现场视频" prop="ProblemVideo" labelPosition="top"
					:customStyle="form_item_customStyle">
					<view class="" style="margin-top: 10rpx">
						<!-- <u-upload :fileList="problem_videos" accept="video" @afterRead="afterRead" @delete="deletePic" name="uploadPicture" multiple :maxCount="0" :previewFullImage="true"></u-upload> -->
						<video v-if="problem_videos" :src="problem_videos"></video>
						<u-button v-if="problem_videos" :plain="true" style="width: 100px" type="warning" size="mini"
							@click="clearVideo">清除视频</u-button>
					</view>
				</u-form-item>
				<u-form-item v-if="model.ProblemStatus == '问题验收' " borderBottom label="问题处理图片" prop="ProblemHandlePic" labelPosition="top">
					<view class="u-page__upload-item" v-if="model.ProblemHandlePic">
						<u-upload :fileList="problemHandlePicFileList" name="ProblemHandlePic" multiple :maxCount="0" :previewFullImage="true"></u-upload>
					</view>
				</u-form-item>
			</u-form>
			<view class="approve-line" style="margin-bottom: 100rpx">
				<ProblemApproveFlowViewer :billId="primaryKey + ''" v-if="status == $GC.STATUS.browse" />
			</view>

			<view class="form-footer">
				<u-button v-if="status != $GC.STATUS.browse" class="btn" type="primary" @click="submit">提交</u-button>
				<u-button v-if="status == $GC.STATUS.edit" class="btn" type="error" @click="cancelEdit">取消修改</u-button>
				<u-button v-if="status == $GC.STATUS.browse" class="btn" type="error" @click="
						status = $GC.STATUS.edit;
						isReadonly = false;
					">
					修改
				</u-button>
			</view>
		</view>

		<u-tabbar @change="tabChange" :fixed="true" :placeholder="true" :safeAreaInsetBottom="true">
			<!-- <u-tabbar-item text="录音" icon="volume"></u-tabbar-item> -->
			<u-tabbar-item text="随手拍" icon="camera"></u-tabbar-item>
			<u-tabbar-item text="视频" icon="play-right"></u-tabbar-item>
		</u-tabbar>

		<u-datetime-picker closeOnClickOverlay @confirm="
				(obj) => {
					dateTimePickerCallBack(obj, 'ProblemStatrTime', 'showStartTimeDateTimePicker');
				}
			" @close="showStartTimeDateTimePicker = false" :show="showStartTimeDateTimePicker"
			mode="datetime"></u-datetime-picker>
		<u-datetime-picker closeOnClickOverlay @confirm="
				(obj) => {
					dateTimePickerCallBack(obj, 'problem_endtime', 'showEndTimeDateTimePicker');
				}
			" @close="showEndTimeDateTimePicker = false" :show="showEndTimeDateTimePicker" mode="datetime"></u-datetime-picker>
		<u-picker closeOnClickOverlay :show="showPicker" @close="showPicker = false" @cancel="showPicker = false"
			@confirm="pickerConfirmEve" :columns="pickerColumns"></u-picker>
	</view>
</template>
<script>
	//录音
	/* const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	 */
	import formRuls from './form_rules';
	import ProblemApproveFlowViewer from '../../takephoto/pub/approve-flow.vue';

	export default {
		name: 'card',
		components: {
			ProblemApproveFlowViewer //审批明细
		},
		data() {
			return {
				showUploadPop: false, //文件上传进度pop弹出层
				percentage: 0, //文件上传进度

				//form-item 自定义样式
				form_item_customStyle: 'padding:18px 0px;font-family:"PingFang SC Regular"; color:"red" ; ',
				form_label_Style: {
					'font-weight': 'bold'
				},

				// datatimepicker 参数 start
				showStartTimeDateTimePicker: false,
				showEndTimeDateTimePicker: false,
				dateTimePickerCfg: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true
				},
				// datatimepicker 参数 end

				// isReadonly: false, //表单是否只读
				status: 'add', //表单状态

				problemPicFileList: [], //照片路径
				problemHandlePicFileList:[], //问题处理照片路径
				problem_videos: '', //视频路径
				pickerCurrentAttrName: '',

				showPicker: false,
				pickerColumns: [],

				primaryKey: '', //主键
				// 表单
				model: {
					ProblemId: '',
					ProblemCode: '',
					ProblemTitle: '',
					pk_org: '',
					ProblemFindByPsn: '',

					ProblemPerson: '',
					ProblemLocation: '',

					ProblemCreDate: uni.$u.timeFormat(Number(new Date()), 'yyyy-mm-dd hh:MM:ss'),
					ProblemStatrTime: uni.$u.timeFormat(Number(new Date()), 'yyyy-mm-dd hh:MM:ss'),
					// problem_endtime: uni.$u.timeFormat(Number(new Date()), 'yyyy-mm-dd hh:MM'),

					ProblemDescription: '',
					ProblemVoice: '',
					ProblemPicture: '',
					ProblemVideo: '',
					ProblemDef1: '',
					ProblemDef4: 'false',
					
					ProblemFlow: '1', //填报类型 1为职能审查流程
					ProblemWorkProcedure: '', //所属工序
					ProblemClassify:'',   //所属班组
					ProblemZnjcFilter: '' //类型负责人
				},
				rules: formRuls, //表单验证规则

				officeSelectList: [],
				userSelectList: [],
				current: 0
			};
		},
		computed: {
			/**
			 * 表单是否只读
			 */
			isReadonly: {
				get() {
					return this.status == this.$GC.STATUS.browse;
				},
				set(newValue) {
					this.status == newValue;
				}
			}
		},
		onShow() {},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			let isWeComPlatform = this.$tool.isWeComPlatform();
			if(isWeComPlatform){
				this.$tool.importQwJsSdk(this.initWeComConfig);
				this.model.ProblemDef4 = true
			}
		},
		onLoad(params) {
			// 获取上一个页面传过来的参数
			this.status = params.status;
			this.primaryKey = params.ProblemId + '';

			let that = this;
			if (this.status == this.$GC.STATUS.add) {
				uni.getStorage({
					key: this.$GC.LOGININFO_KEY,
					success: function(res) {
						that.model.ProblemFindByPsn = res.data.guid;
						let currentUserInfo = uni.getStorageSync(that.$GC.LOGININFO_KEY);
						if (currentUserInfo) {
							that.model.pk_org = currentUserInfo.pk_org;
						}
					}
				});
			}

			if (this.status == this.$GC.STATUS.browse || this.status == this.$GC.STATUS.edit) {
				let queryParam = {
					ProblemId: params.ProblemId
				};
				this.$api
					.queryProblemById(queryParam)
					.then((res) => {
						if (res.success) {
							let problemData = res.data[0];
							let dateTimeFieldArrs = ['ProblemStatrTime', 'ProblemEndTime', 'ProblemCreDate',
								'ProblemUpdDate', 'ProblemAudDate'
							];

							dateTimeFieldArrs.map((item) => {
								if (problemData.hasOwnProperty(item) && problemData[item]) {
									if (problemData[item].includes('T')) {
										// 日期字段格式处理
										problemData[item] = this.$tool.convertISODateToUTC8Date(problemData[
											item]);
									}
								}
							});

							// 图片渲染到页面上
							if (problemData.ProblemPicture) {
								let problemPictureArrs = problemData.ProblemPicture.split('|');
								let tempProblemPicFileList = this.problemPicFileList;

								if (problemPictureArrs.length != 0) {
									problemPictureArrs.map((item) => {
										tempProblemPicFileList.push({
											url: `${this.$GC.API_FS_IP}/${item}`,
											filename: item
										});
									});
								}
								this.problemPicFileList = tempProblemPicFileList;
							}
							// 问题处理图片渲染到页面上
							if (problemData.ProblemHandlePic) {
								let problemPictureArrs = problemData.ProblemHandlePic.split('|');
								let tempProblemPicFileList = this.problemHandlePicFileList;
							
								if (problemPictureArrs.length != 0) {
									problemPictureArrs.map((item) => {
										tempProblemPicFileList.push({
											url: `${this.$GC.API_FS_IP}/${item}`,
											filename: item
										});
									});
								}
								this.problemHandlePicFileList = tempProblemPicFileList;
							}
							// 视频处理
							if (problemData.ProblemVideo) {
								this.problem_videos = `${this.$GC.API_FS_IP}/${problemData.ProblemVideo}`;
							}
							this.model = problemData;
						}
					})
					.catch((error) => {});
			}
		},
		methods: {
			/**
			 * 初始化企业微信配置
			 */
			async initWeComConfig() {
				let that = this;
				let jsapi_ticket = '';
				let agent_ticket = '';
			
				const jsApiResp = await this.$api.getJsApiTicket();
				jsapi_ticket = jsApiResp.Ticket;
				this.jsapi_ticket = jsapi_ticket;
			
				const agentApiResp = await this.$api.getAgentTicket();
				agent_ticket = agentApiResp.Ticket;
				this.agent_ticket = agent_ticket;
			
				const corpid = getApp().globalData.corpid;
				const agentid = getApp().globalData.agentid;
				const corpsecret = '';
				const noncestr = 'gflymob';
				const timestamp = Date.now();
				const signUrl = location.href.split('#')[0];
			
				// 要签名的数据
				const data = `jsapi_ticket=${jsapi_ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${signUrl}`;
				// 进行 SHA-1 签名
				const hash = CryptoJS.SHA1(data);
				// 将签名结果转换为字符串
				const signature = hash.toString(CryptoJS.enc.Hex);
			
				// 所有需要使用JS-SDK的页面必须先注入配置信息，否则将无法调用（同一个url仅需调用一次，对于变化url的SPA（single-page application）的web app可在每次url变化时进行调用）
				wx.config({
					beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
					debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
					appId: corpid, // 必填，企业微信的corpID，必须是本企业的corpID，不允许跨企业使用
					timestamp: timestamp, // 必填，生成签名的时间戳
					nonceStr: noncestr, // 必填，生成签名的随机串
					signature: signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
					jsApiList: ['checkJsApi', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage'] // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
				});
			
				// 要签名的数据
				const agentData = `jsapi_ticket=${agent_ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${signUrl}`;
				// 进行 SHA-1 签名
				const agentHash = CryptoJS.SHA1(agentData);
				// 将签名结果转换为字符串
				const agentSignature = agentHash.toString(CryptoJS.enc.Hex);
			},
			// 取消修改
			cancelEdit() {
				this.status = this.$GC.STATUS.browse;
				let queryParam = {
					ProblemId: this.model.ProblemId
				};
				this.$api
					.queryProblemById(queryParam)
					.then((res) => {
						if (res.success) {
							let problemData = res.data[0];
							let dateTimeFieldArrs = ['ProblemStatrTime', 'ProblemEndTime', 'ProblemCreDate',
								'ProblemUpdDate', 'ProblemAudDate'
							];

							dateTimeFieldArrs.map((item) => {
								if (problemData.hasOwnProperty(item) && problemData[item]) {
									if (problemData[item].includes('T')) {
										// 日期字段格式处理
										problemData[item] = this.$tool.convertISODateToUTC8Date(problemData[
											item]);
									}
								}
							});

							// 图片处理
							if (problemData.ProblemPicture) {
								this.problemPicFileList = [{
									url: `${this.$GC.API_FS_IP}fs/service/${problemData.ProblemPicture}`
								}];
							}
							// 视频处理
							if (problemData.ProblemVideo) {
								this.problem_videos = `${this.$GC.API_FS_IP}fs/service/${problemData.ProblemVideo}`;
							}
							this.model = problemData;
						}
					})
					.catch((error) => {});
			},
			refDateInputClick() {
				// 只读状态，不调整基础档案页面
				if (this.isReadonly) {
					return false;
				}
				this.showStartTimeDateTimePicker = true;
			},
			refInputClick(e) {
				// 只读状态，不调整基础档案页面
				if (this.isReadonly) {
					return false;
				}
				uni.hideKeyboard();
				let refparam = {
					refType: this.$GC.BASEDOC.PSNDOC,
					queryCondition: {
						pk_org: ''
					}
				};
				if (e == 'pk_org') {
					refparam.refType = this.$GC.BASEDOC.ORG;
				}
				if (e == 'ProblemWorkProcedure') {
					refparam.refType = this.$GC.BASEDOC.WorkProcedure;
					let that = this;
					uni.navigateTo({
						url: '/pages/common/listref/listref?refparam=' + JSON.stringify(refparam),
						events: {
							refPageCallBack: function(data) {
								that.model[e] = data.refid;
								let tempData = {
									"inProblemType": that.model['ProblemType'],
									"inProblemWorkProcedure": data.refid
								}
								that.$api.queryZnscFilter(tempData).then((res) => {
									console.log("res: " + JSON.stringify(res));
									let {
										success,
										data
									} = res;
									if (success, data) {
										let znscFilter = JSON.parse(data)
										that.model['ProblemZnjcFilter'] = znscFilter.pk_psndoc
									}
								})
							}
						},
						success: function(res) {}
					});
					return
				}
				if (e == 'ProblemClassify') {
					refparam.refType = this.$GC.BASEDOC.ClassGroup;
				}
				if (e == 'ProblemZnjcFilter') {
					refparam.refType = this.$GC.BASEDOC.PSNDOC;
				}

				let that = this;
				uni.navigateTo({
					url: '/pages/common/listref/listref?refparam=' + JSON.stringify(refparam),
					events: {
						refPageCallBack: function(data) {
							that.model[e] = data.refid;
						}
					},
					success: function(res) {}
				});
			},
			pickerConfirmEve(e) {
				let val = e.value[0];
				if (this.pickerCurrentAttrName) {
					this.model[this.pickerCurrentAttrName] = val;
				}
				if (this.pickerCurrentAttrName == 'ProblemType') {
					let workProcedure = this.model['ProblemWorkProcedure'];
					if (true) {
						let tempData = {
							"inProblemType": val,
							"inProblemWorkProcedure": workProcedure
						}
						this.$api.queryZnscFilter(tempData).then((res) => {
							let {
								success,
								data
							} = res;
							if (success, data) {
								console.log("res: " + JSON.stringify(res));
								let znscFilter = JSON.parse(data)
								this.model['ProblemZnjcFilter'] = znscFilter.pk_psndoc;
							}
						})
					}
				}
				this.showPicker = false;
			},
			pickerInputEvent(attr_name) {
				if (this.isReadonly) {
					return;
				}
				uni.hideKeyboard();
				if (attr_name == 'ProblemType') {
					this.pickerColumns = [
						['设备', '安全', '环保', '品质', '工艺', '5S', '人事行政', '仪表', '电气', '其他', '公用工程']
					];
				} else if (attr_name == 'ProblemWorkProcedure') {
					this.pickerColumns = [
						['工序', '班组', '具体员工']
					];
				}
				this.pickerCurrentAttrName = attr_name;
				this.showPicker = true;
			},
			// 删除图片
			deletePic(event) {
				let fileName = event.file.filename;
				this.problemPicFileList.splice(event.index, 1);
				if (this.model.ProblemPicture) {
					let tempProblemPictures = this.model.ProblemPicture.split('|');
					let newProbPics = [];
					tempProblemPictures.forEach((item) => {
						if (fileName != item) {
							newProbPics.push(item);
						}
					});
					this.model.ProblemPicture = newProbPics.join('|');
					console.log(this.model.ProblemPicture);
				}
			},

			// 清除视频
			clearVideo() {
				this.problem_videos = '';
			},

			// 新增图片
			async afterRead(event) {
				return;
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this.problemPicFileList.length;
				lists.map((item) => {
					this.problemPicFileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				/* for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						})
					);
					fileListLen++;
				} */
			},

			navTo(url) {
				uni.navigateTo({
					url: url
				});
			},

			// base64转成File文件格式
			convertBase64UrlToFile(base64) {
				let urlData = base64.dataURL;
				let type = base64.type;
				let contentName = base64.contentName;
				let bytes = null;
				if (urlData.split(',').length > 1) {
					//是否带前缀
					bytes = window.atob(urlData.split(',')[1]); // 去掉url的头，并转换为byte
				} else {
					bytes = window.atob(urlData);
				}
				// 处理异常,将ascii码小于0的转换为大于0
				let ab = new ArrayBuffer(bytes.length);
				let ia = new Uint8Array(ab);
				for (let i = 0; i < bytes.length; i++) {
					ia[i] = bytes.charCodeAt(i);
				}
				let result = new Blob([ab], {
					type: type
				});
				let result1 = new File([result], contentName, {
					type: type
				});
				result1.path = window.URL.createObjectURL(result);
				return result1;
			},
			// 压缩图片
			compressImage(urlData) {
				let _this = this;
				const asyncFunc = new Promise((resolve) => {
					uni.getImageInfo({
						src: urlData.path,
						success(res) {
							let originWidth = res.width; //图片原始宽
							let originHeight = res.height; //图片原始高
							let img = new Image();
							img.src = res.path;
							let canvas = document.createElement('canvas');
							let ctx = canvas.getContext('2d');
							// 目标尺寸
							let targetWidth = originWidth;
							let targetHeight = originHeight;
							canvas.width = targetWidth;
							canvas.height = targetHeight;
							// 图片压缩
							ctx.drawImage(img, 0, 0, targetWidth, targetHeight);
							let base64;
							// 将png格式文件转为jepg输出，因为png图片不能用这种方式进行压缩
							let filetype = urlData.type === 'image/png' ? 'image/jpeg' : urlData.type;
							// canvas对图片进行缩放 0.5是我定义的图片质量
							if (urlData.size < 1 * 1024 * 1024) {
								// 如果图片小于一兆 那么压缩0.5
								base64 = canvas.toDataURL(filetype, 0.5);
							} else if (urlData.size > 1 * 1024 * 1024 && urlData.size < 2 * 1024 * 1024) {
								// 如果图片大于1M并且小于2M 那么压缩0.5
								base64 = canvas.toDataURL(filetype, 0.5);
							} else {
								// 如果图片超过2m 那么压缩0.2
								base64 = canvas.toDataURL(filetype, 0.2);
							}
							// 将base64转换为filel流
							let flie = _this.convertBase64UrlToFile({
								dataURL: base64,
								type: urlData.type,
								contentName: urlData.name
							});
							resolve(flie);
						},
						fail() {
							uni.showModal({
								title: '提示',
								content: '图片压缩失败',
								showCancel: false
							});
						}
					});
				});
				return asyncFunc;
			},

			tabChange(index) {
				let isWeComPlatform = this.$tool.isWeComPlatform();
				if (isWeComPlatform){
					this.fileUpload4WeComHandler(index);
				}else{
					this.fileUploadHandler(index);
				}
			},
			
			fileUploadHandler(index){
				let that = this;
				// 时间关系，录音功能暂时搁置开发
				// 图片上传
				if (index == 0) {
					uni.chooseImage({
						count: 1, //默认9
						sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album', 'camera'], //从相册选择
						success: function(res) {
							const tempFilePaths = res.tempFilePaths;
							that.uploadFileToGxObject('ProblemPicture', res.tempFiles, tempFilePaths);
						}
					});
				}
				if (index == 1) {
					uni.chooseVideo({
						mediaType: ['video'],
						maxDuration: 30,
						camera: 'back',
						sourceType: ['camera', 'album'],
						success: function(res) {
							that.problem_videos = res.tempFilePath;
				
							const tempFile = res.tempFile;
							const tempFilePath = res.tempFilePath;
				
							that.uploadFileToGxObject('ProblemVideo', [tempFile], [tempFilePath]);
						}
					});
				}
			},
			
			fileUpload4WeComHandler(index){
				// 图片上传
				if (index == 0) {
					this.chooseImage4WeCom();
				}
				if (index == 1) {
					uni.chooseVideo({
						mediaType: ['video'],
						maxDuration: 30,
						camera: 'back',
						sourceType: ['camera', 'album'],
						success: function (res) {
							that.problem_videos = res.tempFilePath;
							
							const tempFile = res.tempFile;
							const tempFilePath = res.tempFilePath;
							
							console.log('视频选择完成' + JSON.stringify(res));
							that.uploadFileToGxObject('ProblemVideo', [tempFile], [tempFilePath]);
						}
					});
				}
			},
			
			/**
			 * 图片上传
			 */
			async chooseImage4WeCom() {
				let that = this;
				wx.ready(function () {
					// config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，
					// 所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
					wx.chooseImage({
						count: 5, // 默认9
						sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
						defaultCameraMode: 'normal', //表示进入拍照界面的默认模式，目前有normal与batch两种选择，normal表示普通单拍模式，batch表示连拍模式，不传该参数则为normal模式。从3.0.26版本开始支持front和batch_front两种值，其中front表示默认为前置摄像头单拍模式，batch_front表示默认为前置摄像头连拍模式。（注：用户进入拍照界面仍然可自由切换两种模式）
						isSaveToAlbum: 1, //整型值，0表示拍照时不保存到系统相册，1表示自动保存，默认值是1
						success: function (res) {
							var localIds = res.localIds; // 返回选定照片的本地ID列表，
							// andriod中localId可以作为img标签的src属性显示图片；
							// iOS应当使用 getLocalImgData 获取图片base64数据，从而用于img标签的显示（在img标签内使用 wx.chooseImage 的 localid 显示可能会不成功）
							let localId = localIds[0];
							let tempProblemPicFileList = [];
							localIds.forEach((tempLocalId) => {
								if (that.$tool.isIosPlatform()) {
									wx.getLocalImgData({
										localId: tempLocalId, // 图片的localID
										success: function (res) {
											var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
											tempProblemPicFileList.push({
												url: localData
											});
										}
									});
								} else {
									tempProblemPicFileList.push({
										url: tempLocalId
									});
								}
								wx.uploadImage({
									localId: tempLocalId, // 需要上传的图片的本地ID，由chooseImage接口获得
									isShowProgressTips: 1, // 默认为1，显示进度提示
									success: function (res) {
										var serverId = res.serverId; // 返回图片的服务器端ID
										// 将文件名放置到form表单，需要传给后端，因为是多文件上传，所以拼接|符号
										// ProblemDef7字段用来备份企微media id
										if (that.model['ProblemPicture']) {
											that.model['ProblemPicture'] += '|' + serverId;
											that.model['ProblemDef7'] += '|' + serverId;
										} else {
											that.model['ProblemPicture'] = serverId;
											that.model['ProblemDef7'] = serverId
										}
									}
								});
							});
			
							that.problemPicFileList = tempProblemPicFileList;
						}
					});
				});
				wx.error(function (res) {});
			},
			
			/**
			 * @param {String} formAttrName
			 * @param {Array} files
			 * @param {Array} filePath
			 * @param {Object} formData
			 */
			uploadFileToGxObject(formAttrName, files, filePath, formData) {
				let that = this;
				let url = this.$GC.FILE_UPLOAD_URL;
				let authorization = uni.getStorageSync(this.$GC.ACCESS_TOKEN_KEY);

				let header = {
					Authorization: authorization
				};
				console.log('uploadFileToGxObject方法被调用');

				// 上传进度条
				this.showUploadPop = true;
				this.percentage = 0;

				// 1. 第一步，先调用gxobject上传文件资源
				const uploadTask = uni.uploadFile({
					url: url,
					file: files[0],
					filePath: filePath[0],
					header: header,
					name: 'UploadFiles',
					formData: {},
					success: (res) => {
						console.log('调用gxobject方法的返回值: ' + JSON.stringify(res));

						let resStr = res.data;
						let replaceStr = '{"error":{"code":500,"message":"Internal Server Error"}}';
						resStr = resStr.replace(replaceStr, '');
						let fileUploadRes = JSON.parse(resStr);
						console.log('调用gxobject方法的返回值fileUploadRes: ' + JSON.stringify(fileUploadRes));

						// 2. 第二步，调用上传文件业务接口，保存文件到具体磁盘上
						let fileUploadParam = {
							FileId: '',
							FileFullName: '',
							tempFile: ''
						};

						let tempFiles = fileUploadRes.files;
						tempFiles.map((tempFile) => {
							let paths = tempFile.path.split(':');
							let fileId = paths[1];

							fileUploadParam.FileFullName = fileId + '_' + tempFile
								.name; //compress_video_19463086.mp4
							fileUploadParam.tempFile = tempFile
								.path; //"gxupload:551699aa47b74c6eabaa46874ee8fb11"
							fileUploadParam.FileId = fileId;
						});

						that.$api
							.fileUpload(fileUploadParam)
							.then((res) => {
								// 将文件名放置到form表单，需要传给后端，因为是多文件上传，所以拼接|符号
								if (that.model[formAttrName]) {
									that.model[formAttrName] += '|' + fileUploadParam.FileFullName;
								} else {
									that.model[formAttrName] = fileUploadParam.FileFullName;
								}

								if (formAttrName == 'ProblemPicture') {
									// 将图片渲染到页面上
									let problemPictures = that.problemPicFileList;
									problemPictures.push({
										url: `${that.$GC.API_FS_IP}/${fileUploadParam.FileFullName}`,
										filename: fileUploadParam.FileFullName
									});
									that.problemPicFileList = problemPictures;
								}

								that.percentage = 100;
								that.showUploadPop = false;
								let params = {
									duration: 1500,
									type: 'success',
									icon: '@/static/icon/success.png',
									message: '文件上传完成！'
								};

								that.$refs.uToast.show({
									...params,
									complete() {}
								});
							})
							.catch((error) => {
								that.$tool.msg('文件上传失败！');
								that.model[formAttrName] = '';
							});
					},
					fail: (e) => {
						that.$tool.msg('文件上传失败！');
						that.model[formAttrName] = '';
					},
					complete: (e) => {}
				});

				// 通过 uploadTask，可监听上传进度变化事件，以及取消上传任务。
				uploadTask.onProgressUpdate((res) => {
					if (res.progress == 100) {
						// 此处需要暂停一下，防止gxobject调用完了，fileupload接口超时的情况
						that.percentage = 99;
					} else {
						that.percentage = res.progress;
					}
				});
			},

			submit() {
				//未启用的自定义项，不传给后端
				delete this.model['ProblemDef11']
				delete this.model['ProblemDef12']
				delete this.model['ProblemDef13']
				delete this.model['ProblemDef14']
				delete this.model['ProblemDef15']
				delete this.model['ProblemDef16']
				delete this.model['ProblemDef17']
				delete this.model['ProblemDef18']
				delete this.model['ProblemDef19']
				delete this.model['ProblemDef20']
				this.model.ProblemTitle = this.model.ProblemDescription.substring(0, 200);
				this.$refs.uForm
					.validate()
					.then((res) => {
						this.$api
							.insertProblem(this.model)
							.then((res) => {
								let msgStr = '';
								if (res.code != 200) {
									let msgArrs = JSON.parse(res.message);
									if (Array.isArray(msgArrs)) {
										msgArrs.map((item) => {
											msgStr += item;
										});
									}
								} else {
									msgStr = res.message;
								}
								uni.showModal({
									title: '提示',
									content: msgStr,
									showCancel: false,
									success: function() {
										if (res.success) {
											uni.navigateBack({
												success() {
												},
												complete(){
													//清空表单，防止页面跳转失败，数据重复提交
													that.model.ProblemLocation = '';
													that.model.ProblemDescription ='';
													that.model.ProblemPicture = '';
													that.model.ProblemVideo = '';
												}
											});
										}
									}
								});
							})
							.catch((error) => {});
					})
					.catch((errors) => {
						uni.$u.toast('表单校验失败！');
					});
			},
			cancel() {
				uni.navigateBack();
			},
			dateTimePickerCallBack(obj, attr_name, component_id) {
				this[`${component_id}`] = false;
				let value = obj.value;
				const timeFormat = uni.$u.timeFormat,
					toast = uni.$u.toast;
				if (attr_name == '') return;
				if (value == '') {
					this.model[attr_name] = '';
				} else {
					value = timeFormat(value, 'yyyy-mm-dd hh:MM:ss');
					this.model[attr_name] = value;
				}
			}
		}
	};
</script>
<style lang="scss">
	/deep/ .u-tabbar-item__text {
		font-size: 13px;
	}
</style>